package dfl.bysj.controller;


import cn.hutool.core.io.file.PathUtil;
import com.aliyun.oss.model.OSSObject;
import dfl.bysj.config.QRCodeGenerator;
import dfl.bysj.entity.VO.Form_value;
import dfl.bysj.handler.NoAuth;
import dfl.bysj.result.R;
import dfl.bysj.service.FileService;
import dfl.bysj.service.SeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author DFL
 * @since 2022-05-17
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/seat")
public class SeatController {

    private SeatService seatService;

    private FileService fileService;

    @Autowired
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @Autowired
    public void setSeatService(SeatService seatService) {
        this.seatService = seatService;
    }

    @NoAuth
    @GetMapping("/list")
    public R list() {
        return R.ok().data("list", seatService.getAllSeatVO());
    }

    @PostMapping(value = "/insert", produces = "application/json;charset=UTF-8")
    public R insert(@RequestBody Form_value form_value) {
        log.info(form_value.toString());
        seatService.insertSeat(form_value);
        return R.ok();
    }


    @GetMapping("/qrcode")
    public R generateQRcode() {
        seatService.generateQRCode();
        return R.ok();
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request) {
        try {
            String momentFileName = "座位二维码.zip";
            // 创建临时文件
            File zipFile = File.createTempFile("批量下载", ".zip");
            FileOutputStream f = new FileOutputStream(zipFile);
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            ZipOutputStream zos = new ZipOutputStream(csum);
            List<String> objectName=seatService.getAllQRCodeName();
            for (String string : objectName) {
                log.info(string);
//                String eachFileName = fName.substring(fName.lastIndexOf("/") + 1);
//                String tmp = fName.substring(0, fName.lastIndexOf("/"));
//                tmp = tmp.substring(tmp.lastIndexOf("/") + 1);
//                String fileName = tmp + "/" + eachFileName;
                log.info(response.getOutputStream().toString());
                OSSObject ossObject = fileService.downloadOssFile(response.getOutputStream(), string);

                InputStream inputStream = ossObject.getObjectContent();
                zos.putNextEntry(new ZipEntry(string));
                int bytesRead;
                // 向压缩文件中输出数据
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry();
            }
            zos.close();
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                momentFileName = URLEncoder.encode(momentFileName, "utf-8");
                momentFileName = momentFileName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                momentFileName = new String(momentFileName.getBytes(), "ISO8859-1");
            }
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", momentFileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + momentFileName);
            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] car = new byte[1024];
            int l = 0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();
            // 删除临时文件
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

